package com.cyq.dascma.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cyq.dascma.constant.ValidaEnum;
import com.cyq.dascma.entity.Student;
import com.cyq.dascma.entity.Teacher;
import com.cyq.dascma.exception.ServiceException;
import com.cyq.dascma.handler.valida.impl.StudentValidaImpl;
import com.cyq.dascma.handler.valida.impl.TeacherValidaImpl;
import com.cyq.dascma.result.Result;
import com.cyq.dascma.result.ResultGenerator;
import com.cyq.dascma.service.TeacherService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * 教师模块控制器
 * dingwen
 * 2021/3/30 22:53
 **/
@Api(tags = "教师模块")
@RestController
@RequestMapping("/teacher")
public class TeacherController {
    private final TeacherService teacherService;

    @Autowired
    TeacherController(TeacherService teacherService) {
        this.teacherService = teacherService;
    }

    /*
     *分页查询所有教师列表
     * 带条件的分页查询
     * @param []
     * @return com.cyq.dascma.result.Result
     */
    @ApiOperation(value = "分页查询所有教师列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "teacherId", value = "教工号", required = false),
            @ApiImplicitParam(name = "teacherName", value = "教师姓名", required = false),
            @ApiImplicitParam(name = "teacherLevel", value = "教师权限【0：普通教师 1:班主任 2：管理员】", required = false),
            @ApiImplicitParam(name = "pageSize", value = "每页多少条", required = true),
            @ApiImplicitParam(name = "pageNum", value = "第几页", required = true),
    })
    @GetMapping("/page")
    public Result get(@RequestParam(value = "teacherId", required = false) String teacherId,
                      @RequestParam(value = "teacherName", required = false) String teacherName,
                      @RequestParam(value = "teacherLevel", required = false) Integer teacherLevel,
                      @RequestParam(value = "pageSize") Integer pageSize,
                      @RequestParam(value = "pageNum") Integer pageNum) {


        // 创建分页对象
        Page<Teacher> teacherPage = new Page<>(pageNum, pageSize);

        //构建查询条件
        QueryWrapper<Teacher> teacherQueryWrapper = new QueryWrapper<>();

        if (StringUtils.hasText(teacherId)) {
            teacherQueryWrapper.eq("teacher_id", teacherId);
        }

        if (StringUtils.hasText(teacherName)) {
            teacherQueryWrapper.like("teacher_name", teacherName);
        }

        if (teacherLevel != null) {
            teacherQueryWrapper.eq("teacher_level", teacherLevel);
        }
        IPage<Teacher> teacherIPage = teacherService.page(teacherPage, teacherQueryWrapper);
        return ResultGenerator.genOkResult(teacherIPage);
    }

    /*
     *修改教师信息
     * @param [teacher]
     * @return com.cyq.dascma.result.Result
     */
    @ApiOperation("修改教师信息")
    @ApiImplicitParam(name = "teacher", value = "教师实体", required = true, dataType = "student", paramType = "body")
    @PutMapping("/modify")
    public Result modify(@RequestBody Teacher teacher) {
        try {
            new TeacherValidaImpl().valida(ValidaEnum.MODIFY, teacher);
        } catch (ServiceException serviceException) {
            return serviceException.result();
        }
        boolean flag = teacherService.updateById(teacher);
        return flag ? ResultGenerator.genOkResult(teacher) : ResultGenerator.genFailureResult("更新教师信息失败");
    }

    /*
     *根据教工号删除教师信息
     * @param [teacherId]
     * @return com.cyq.dascma.result.Result
     */
    @ApiOperation("根据教工号删除教师信息")
    @ApiImplicitParam(value = "教工号", name = "teacherId", required = true, dataType = "String")
    @DeleteMapping("/remove/{teacherId}")
    public Result remove(@PathVariable(value = "teacherId") String teacherId) {
        boolean flag = teacherService.removeById(teacherId);
        return flag ? ResultGenerator.genOkResult(teacherId) : ResultGenerator.genFailureResult("删除教师信息失败");
    }


    /*
     * 【普通教师、班主任、管理员】用户登录
     * @param student
     * @return Result
     */
    @ApiOperation("【普通教师、班主任、管理员】用户登录")
    @ApiImplicitParam(name = "teacher", value = "教师实体", required = true, dataType = "teacher", paramType = "body")
    @PostMapping("/login")
    public Result login(@RequestBody Teacher teacher, HttpServletRequest request, HttpServletResponse response) {
        try {
            new TeacherValidaImpl().valida(ValidaEnum.LOGIN, teacher);
        } catch (ServiceException serviceException) {
            return serviceException.result();
        }
        QueryWrapper<Teacher> teacherQueryWrapper = new QueryWrapper<>();
        teacherQueryWrapper.and(wrapperById -> wrapperById.eq("teacher_id", teacher.getTeacherId()))
                .and(wrapperByPassword -> wrapperByPassword.eq("teacher_password", teacher.getTeacherPassword()));
        Teacher teacherOne = teacherService.getOne(teacherQueryWrapper);
        request.getSession().setAttribute("user", teacherOne);
//        Cookie cookie = new Cookie("JSESSIONID", session.getId());
//        cookie.setMaxAge(60 * 60);
//        response.addCookie(cookie);
        return teacherOne == null ? ResultGenerator.genFailureResult("登录失败") : ResultGenerator.genOkResult(teacherOne);
    }

    /*
     *退出登录
     * @param [request]
     * @return com.cyq.dascma.result.Result
     */
    @ApiOperation("退出登录")
    @GetMapping("/logout")
    public Result logout(HttpSession session) {
        session.invalidate();
        return ResultGenerator.genOkResult("ok;");
    }


    /*
     *查询所有教师的ID & name 信息
     * @param []
     * @return com.cyq.dascma.result.Result
     */
    @ApiOperation("查询所有教师的ID & name 信息")
    @GetMapping("/ins")
    public Result get() {
        List<Teacher> teacherList = teacherService.list(new QueryWrapper<Teacher>().select("teacher_id", "teacher_name"));
        return ResultGenerator.genOkResult(teacherList);
    }


    /*
     *查询教师表总记录条数
     * @param []
     * @return com.cyq.dascma.result.Result
     */
    @ApiOperation("查询教师表总记录条数")
    @GetMapping("/total")
    public Result getTotal() {
        return ResultGenerator.genOkResult(teacherService.count());
    }


    /*
     *新增教师信息
     * @param [teacher]
     * @return com.cyq.dascma.result.Result
     */
    @ApiOperation("新增教师信息")
    @ApiImplicitParam(name = "teacher", value = "教师实体", required = true, dataType = "teacher", paramType = "body")
    @PostMapping("/add")
    public Result add(@RequestBody Teacher teacher) {
        try {
            new TeacherValidaImpl().valida(ValidaEnum.ADD, teacher);
        } catch (ServiceException serviceException) {
            return serviceException.result();
        }
        // 默认密码为学号
        teacher.setTeacherPassword(teacher.getTeacherId());
        boolean flag = teacherService.save(teacher);
        return flag ? ResultGenerator.genOkResult() : ResultGenerator.genFailureResult("新增教师失败");
    }


    /*
     *批量删除
     * @param [teacherList]
     * @return com.cyq.dascma.result.Result
     */
    @ApiOperation("批量删除")
    @ApiImplicitParam(name = "teacherList", value = "教师List", paramType = "body")
    @DeleteMapping("/remove/batch")
    public Result remove(@RequestBody List<Teacher> teacherList) {
        List<String> ids = new ArrayList<>();
        teacherList.stream().parallel().forEach(teacher -> ids.add(teacher.getTeacherId()));
        boolean flag = teacherService.removeByIds(ids);
        return flag ? ResultGenerator.genOkResult() : ResultGenerator.genFailureResult("批量删除失败");
    }

}
